/*
 * @Author: Wangtao
 * @Date: 2020-09-18 11:41:07
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-04-18 11:13:53
 */
const path = require('path')
const { name } = require('./package')
const webpack = require('webpack')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
function resolve (dir) {
  return path.join(__dirname, dir)
}
const array = ['^/sms-api', '^/server-public', '^/server-crm', '^/server-flow', '^/server-work', '^/auth', '^/crm', '^/call', '^/base', '^/im-web', '^/im-center', '^/im-wechat', '^/im-robot', '^/download', '^/upload', '^/im-km', '^/im-sdk', '^/im-wxsdk', '^/im-report', '^/report', '^/im-third-party'] // 请求代理地址分发
var proxyObj = {}
array.forEach((item) => {
  if (item === '^/sms-api') {
    proxyObj[item] = {
      target: 'https://test-v7-sms.7moor.com',
      ws: false,
      changeOrigin: true
    }
  } else {
    proxyObj[item] = {
      // target: 'https://dev1-v7.7moor.com/',
      target: 'https://test1-v7.7moor.com',
      // target: 'http://152.136.72.209:6100',
      ws: true,
      changeOrigin: true
    }
  }
})
const pagesMicro = { // 微前端多页面入口
  microWebchat: {
    // page 的入口
    entry: 'src/microPage/webchat/main.ts',
    template: 'src/microPage/webchat/index.html',
    chunks: ['runtime~microWebchat', 'chunk-vendors', 'chunk-common', 'microWebchat']
  },
  microWebchatSession: {
    // page 的入口
    entry: 'src/microPage/webchatSession/main.ts',
    template: 'src/microPage/webchatSession/index.html',
    chunks: ['runtime~microWebchatSession', 'chunk-vendors', 'chunk-common', 'microWebchatSession']
  }
}
const mainPage = { // 主页面
  index: {
    // 页面入口
    entry: 'src/main.ts',
    template: '/index.html'
  }
}
const pages = process.env.VUE_APP_ENTRY === 'main' ? mainPage : pagesMicro
const prefetch = process.env.VUE_APP_ENTRY === 'main' ? 'prefetch-index' : 'prefetch-microWebchat'
module.exports = {
  publicPath: '/',
  // 输出文件目录
  outputDir: 'dist',
  // eslint-loader 是否在保存的时候检查
  lintOnSave: process.env.NODE_ENV !== 'production',
  chainWebpack: (config) => {
    config.plugins.delete(prefetch) // 禁止预加载js
    if (process.env.VUE_APP_ENTRY !== 'main') {
      config.plugins.delete('prefetch-microWebchatSession') // 禁止预加载js
    }
    config.resolve.alias
      .set('@', resolve('./src'))
      .set('src', resolve('./src'))
      .set('@utils', resolve('./src/utils'))
      .set('@assets', resolve('./src/assets'))
      .set('@modules', resolve('./src/store/modules'))
      .set('@components', resolve('./src/components'))
      .set('@views', resolve('./src/views'))
      .set('@after', resolve('./src/afterSales'))
      .set('@microPage', resolve('./src/microPage'))
      .set('@api', resolve('./src/store/api'))
    config.module
      .rule('cur')
      .test(/\.cur$/)
      .use('url')
      .loader('url-loader')
    config.plugin('fork-ts-checker').tap(([options]) => { // ts报错终止程序进行，直到把报错解决完
      return [{
        async: true,
        tslint: true,
        vue: true
      }]
    })
    if (process.env.NODE_ENV === 'production') {
      config.plugin('vendorDll')
        // 这个插件把只有 dll 的 bundle(们)(dll-only-bundle(s)) 引用到需要的预编译的依赖
        // 通过引用 dll 的 manifest 文件来把依赖的名称映射到模块的 id 上，之后再在需要的时候通过内置的 __webpack_require__ 函数来 require 他们
        .use(webpack.DllReferencePlugin, [{
          context: process.cwd(),
          manifest: require('./public/vendor/vendor-manifest.json')
        }])
    }
    // 自动引入生成的 dll 文件
    config.plugin('addAssetHtml')
      // 将 dll 注入到 生成的 html 模板中
      .use(AddAssetHtmlPlugin, [
        [
          {
            // dll文件位置
            filepath: path.resolve(__dirname, './public/vendor/*.js'),
            // dll 引用路径
            publicPath: '/vendor',
            // dll最终输出的目录
            outputPath: '/vendor'
          }
        ]
      ])
      .after('html')

    // config
    //   .plugin('webpack-bundle-analyzer')
    //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
  },
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  // css相关配置
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: false,
    // 开启 CSS source maps?
    sourceMap: false,
    // css预设器配置项
    loaderOptions: {
      stylus: {
        // 全局引入css变量
        import: '~@/common/style/common.styl'
      }
    },
    // 启用 CSS modules for all css / pre-processor files.
    requireModuleExtension: true
  },
  // use thread-loader for babel & TS in production build
  // enabled by default if the machine has more than 1 cores
  parallel: require('os').cpus().length > 1,
  // PWA 插件相关配置
  // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwass
  pwa: {},
  pages: pages,
  devServer: {
    port: 3001, // 8080
    hot: true,
    open: true,
    proxy: proxyObj,
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  },
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      const options = config.optimization.minimizer[0].options
      options.terserOptions.compress.drop_console = true
      const terserPlugin = new TerserPlugin(options)
      config.optimization.minimizer = [terserPlugin]
      // config.optimization.runtimeChunk = true
    }
    if (process.env.VUE_APP_ENTRY === 'micro') {
      config.output.library = `${name}-[name]`
      config.output.libraryTarget = 'umd'
      config.output.jsonpFunction = `webpackJsonp_${name}`
    }
  },
  // 第三方插件配置
  pluginOptions: {
    // ...
  }
}
